# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'KWWA94028ZFVJ': {
        'API_KEY': 'XRMYTWZHFEHCNSYKHRRUOZGWCHGJPGGU',
        'cert_no': '20180408223947469028',
        'password': '!qb=k=',
        'gateway': 'http://gw.365shangcheng999.com/native/com.opentech.cloud.easypay.trade.create/0.0.1',
        'query_gateway': 'https://payment.sc365pay.com.tw/tpayv3/checkorder.aspx',
    },
    '88888888': {
        'API_KEY': 'sfoiuqfjijsfosdf232342jkjnkjhfhfh23234234',
        'cert_no': '2017011822055618000',
        'password': '!qb=k=',
        'gateway': 'http://gw.365shangcheng999.com/native/com.opentech.cloud.easypay.trade.create/0.0.1',
        'query_gateway': 'https://payment.sc365pay.com.tw/tpayv3/checkorder.aspx',
        'info': '测试账号',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_cert_no(mch_id):
    return APP_CONF[mch_id]['cert_no']


def _get_password(mch_id):
    return APP_CONF[mch_id]['password']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_order_sign(url, header, body, key):
    s = url
    for k in header:
        if k.startswith('x-oapi'):
            s += '&{}={}'.format(k, header[k])
    s += '&' + body
    s += '&' + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(parameter, key):
    s = '{}&{}:{}'.format(parameter['scode'], parameter['orderid'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    _LOGGER.info(u'sc365pay origin string: %s, sign:%s', s, sign)
    return sign


def verify_notify_sign(data, url, header, sign, key):
    s = url
    for k in header:
        s += '&{}={}'.format(k, header[k])
    s += '&' + data
    s += '&' + key
    _LOGGER.info('sigggggggggn: %s', s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    calculated_sign = m.hexdigest()
    if base64.b64decode(sign) != calculated_sign:
        _LOGGER.info("sc365pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % data)


# UNION_PAY : PC银联快捷⽀付
# H5_UNION_PAY : H5银联快捷⽀付
# ALIPAY_QUICK_PAY : ⽀付宝快捷⽀付
# WECHAT_QUICK_PAY : 微信快捷⽀付
# QQ_QUICK_PAY : QQ快捷⽀付
# JD_QUICK_PAY : 京东快捷⽀付
# H5: ⽹关⽀付
def _get_pay_type(service):
    if service == 'wxpay':
        paytype = 'WECHAT_QUICK_PAY'
    elif service == 'quick':
        paytype = 'H5_UNION_PAY'
    elif service == 'qq':
        paytype = 'QQ_QUICK_PAY'
    elif service == 'jd':
        paytype = 'JD_QUICK_PAY'
    else:
        paytype = 'ALIPAY_QUICK_PAY'
    return paytype


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    key = _get_api_key(app_id)
    service = info.get('service')

    p_dict = OrderedDict((
        ('merchantNo', app_id),
        ('outTradeNo', str(pay.id)),
        ('currency', 'CNY'),
        ('amount', str(int(pay_amount * 100))),
        ('payType', _get_pay_type(service)),
        ('content', 'charge'),
        ('callbackURL', '{}/pay/api/{}/sc365pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    h_dict = OrderedDict((
        ('http-x-oapi-pv', '0.0.1'),
        ('http-x-oapi-sdkv', '0.0.1'),
        ('http-x-oapi-sk', _get_cert_no(app_id)),
        ('http-x-oapi-sm', 'MD5'),
    ))
    j = json.dumps(p_dict, separators=(',', ':'))
    url = _get_gateway(app_id)

    headers = {'Content-Type': 'application/json;charset=utf-8'}
    for h, value in h_dict.iteritems():
        headers[h] = value
    headers['x-oapi-sign'] = generate_order_sign(url, h_dict, j, key)

    response = requests.post(url, data=j, headers=headers, timeout=3).json()
    _LOGGER.info(u'sc365pay origin data: %s', p_dict)
    return {'charge_info': response['paymentInfo']}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = request.body
    url = '{}/pay/api/{}/sc365pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)
    _LOGGER.info("%s", request.META)
    sign = request.META['HTTP_X_OAPI_SIGN']
    h_dict = OrderedDict((
        ('x-oapi-pv', '0.0.1'),
        ('x-oapi-sdkv', '0.0.1'),
        ('x-oapi-sk', _get_cert_no(app_id)),
        ('x-oapi-sm', 'MD5'),
    ))
    _LOGGER.info("sc365pay notify data: %s", data)
    verify_notify_sign(data, url, h_dict, sign, key)
    pay_id = data['outTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('sc365pay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data.get('tradeNo')
    total_fee = float(data['payedAmount']) / 100

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SETTLED':
        _LOGGER.info('sc365pay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'scode': app_id,
        'orderid': str(pay_id),
    }
    p_dict['sign'] = generate_query_sign(p_dict, key)
    _LOGGER.info(u'sc365pay query data: %s', p_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=p_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info(u'sc365pay query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['status'])
        trade_no = data['orderno']
        total_fee = float(data['amount'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('sc365pay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('sc365pay data error, status_code: %s', response.status_code)


if __name__ == '__main__':
    app_id = 'KWWA94028ZFVJ'
    # app_id = '88888888'
    key = _get_api_key(app_id)
    service = 'quick'
    p_dict = OrderedDict((
        ('merchantNo', app_id),
        ('outTradeNo', '%s' % random.randint(10000, 99999)),
        ('currency', 'CNY'),
        ('amount', 100),
        ('payType', _get_pay_type(service)),
        ('content', 'charge'),
        ('callbackURL', 'http://www.baidu.com/'),
    ))
    h_dict = OrderedDict((
        ('x-oapi-pv', '0.0.1'),
        ('x-oapi-sdkv', '0.0.1'),
        ('x-oapi-sk', _get_cert_no(app_id)),
        ('x-oapi-sm', 'MD5'),
    ))
    j = json.dumps(p_dict, separators=(',', ':'))
    url = _get_gateway(app_id)

    headers = {'Content-Type': 'application/json;charset=utf-8'}
    for h, value in h_dict.iteritems():
        headers[h] = value
    headers['x-oapi-sign'] = generate_order_sign(url, h_dict, j, key)

    response = requests.post(url, data=j, headers=headers).json()
    print response['paymentInfo']
